package cn.rgb.common;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class BeanUtilsx {

	public static Object newInstance(String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		return newInstance(Class.forName(className));
	}
	
	public static Object newInstance(Class<?> cls) throws InstantiationException, IllegalAccessException {
		return cls.newInstance();
	}
	
	public static List<Object> getFieldValues(List<String> fields, Object target) {
		Class<?> cls = target.getClass();
		int size = fields.size();
		List<Object> values = new ArrayList<Object>(size);
		for(int index = 0; index < size; index++) {
			values.add(getFieldValue(cls, fields.get(index), target));
		}
		return values;
	}
	
	public static Object getFieldValue(Class<?> cls, String field, Object target) {
		Object returnObject = null;
		try {
			Method method = getGetMethod(cls, field);
			returnObject = method.invoke(target, new Object[]{});
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return returnObject;
	}
	
	private static Method getGetMethod(Class<?> cls, String field) throws NoSuchMethodException {
		Method method = null;
		try {			
			method = getGetMethod(cls, field, "get");
		} catch(NoSuchMethodException e) {
		}
		try {			
			if(method == null || method.getReturnType().equals(Boolean.TYPE)) {
				method = getGetMethod(cls, field, "is");
				if(method != null && !method.getReturnType().equals(Boolean.TYPE))
					method = null;
			}
		} catch(NoSuchMethodException e) {
		}
		if(method == null) {
			throw new NoSuchMethodException("There is no public method(getXxx() or isXxx()) with field: " + field);
		}
		return method;
	}
	
	private static Method getGetMethod(Class<?> cls, String field, String prefix) throws NoSuchMethodException {
		String methodName = prefix + Character.toUpperCase(field.charAt(0)) + field.substring(1);
		return cls.getMethod(methodName, new Class[]{});
	}
	
	
	public static void setFieldValue(String field, String value, Object target) {
		
	}
}
